<template>
  <view class="root-page">
    <view class="item box-border m-2 rounded-sm" v-for="(res, index) in siteList" :key="res.customerInformationItemId">
      <view class="top items-center" @click="selectedCkick(res)">
        <view class="name">{{ res.itemName }}</view>
        <view class="phone">{{ res.phone }}</view>
        <view class="tag">
          <text class="df-color" v-if="res.isDefault == '1'">默认</text>
        </view>
        <!-- <view class="tag">
					<text v-for="(item, index) in res.tag" :key="index" :class="{ red: item.isDefault == '1' }">{{ item.isDefault
						}}</text>
				</view> -->
      </view>
      <view class="bottom" @click="selectedCkick(res)">
        <text>{{ res.itemAddress }} - {{ res.receiveHouseNumber }}</text>
        <!-- <u-icon name="edit-pen" size="40rpx" color="#999999"></u-icon> -->
      </view>
      <u-line margin="0.5em 0" />
      <view class="bottom">
        <view class="flex-row flex-1 justify-center text-center" @click="setDefault(res)">
          <u-icon name="pushpin" size="40rpx" color="#0175ff" label="设为默认"></u-icon>
          <!-- <text>设为默认</text> -->
        </view>
        <u-line margin="0 1em" color="grey" length="1rem" direction="col" />
        <view class="flex-row flex-1 justify-center" @click="toAddSite(res)">
          <u-icon name="edit-pen" size="40rpx" color="#0175ff" label="编辑"></u-icon>
          <!-- <text>编辑</text> -->
        </view>
        <u-line margin="0 1em" color="grey" length="1rem" direction="col" />
        <view class="flex-row justify-cente flex-1 justify-center" @click="delAddSite(res)">
          <u-icon name="trash" size="40rpx" color="#0175ff" label="删除"></u-icon>
          <!-- <text>删除</text> -->
        </view>
      </view>
    </view>
    <view>
      <u-empty
        v-if="siteList.length == 0"
        mode="data"
        text="暂无地址数据"
        :icon="'/static/images/state/state_no_list.png'"
      ></u-empty>
    </view>
    <view class="addSite" @tap="toAddSite">
      <view class="add"> <u-icon name="plus" color="#ffffff" class="icon" size="30rpx"></u-icon>新建收货地址 </view>
    </view>
  </view>
</template>

<script>
import { addrList, delAddrById, addAddr } from "../api/addrManage";
export default {
  data() {
    return {
      doYouWantToChooseAnAddress: false, // 是否是外部打开
      siteList: [],
    };
  },
  onLoad(options) {
    if (options.doYouWantToChooseAnAddress) this.doYouWantToChooseAnAddress = true;
  },
  onShow() {
    this.getData();
  },
  methods: {
    async getData() {
      try {
        const { id } = this.$store.getters.userInfo;
        const pam = {
          itemType: 11,
          // customerInformationId: 1,
          userId: id,
        };
        const { data, success } = await addrList(pam);
        if (!success) return;
        this.siteList = data.records;
      } catch (error) {
        console.error(error);
      }
    },
    toAddSite(item) {
      uni.navigateTo({
        url: `./addSite?id=${item?.customerInformationItemId || ""}`,
      });
    },
    delAddSite(item) {
      uni.showModal({
        title: "提示",
        content: "确定删除该地址吗？",
        success: async (res) => {
          if (!res.confirm) return;
          try {
            const { success } = await delAddrById(item.customerInformationItemId);
            if (!success) throw new Error("删除失败");
            uni.showToast({
              title: "删除成功",
              icon: "none",
            });
            this.getData();
          } catch (error) {
            console.error(error);
            uni.showToast({
              title: error,
              icon: "none",
            });
          }
        },
      });
    },
    setDefault(item) {
      uni.showModal({
        title: "提示",
        content: "确定将该地址设为默认吗？",
        success: async (res) => {
          if (!res.confirm) return;
          try {
            item.isDefault = "1";
            const { success } = await addAddr(item);
            if (!success) throw new Error("更新失败");
            uni.showToast({
              title: "更新成功",
              icon: "none",
            });
            this.getData();
          } catch (error) {
            console.error(error);
            uni.showToast({
              title: error,
              icon: "none",
            });
          }
        },
      });
    },
    // 外部打开（回调地址）
    selectedCkick(item) {
      if (this.doYouWantToChooseAnAddress) {
        // uni.$emit("address", item);
        uni.$emit("address", item);
        uni.navigateBack({
          success() {
            const timer = setTimeout(() => {
              uni.showToast({
                title: "选择成功",
                icon: "none",
              });
              clearTimeout(timer);
            }, 500);
          },
        });
        // return _self.$util.Tips({ title: "选择成功" }, { tab: 3, url: 1 });
      } else this.toAddSite(item);
      // 接受 示例：
      // uni 的 $emit 事件有问题（新增收货地址再选，在这里收不到）,改用 vue 事件总线
      // this.$eventHub.$on("address", (data) => {
      // 	this.address = data;
      // 	if (data) {
      // 		this.$set(this, "address", data);
      // 		this.address.Address = data.itemAddress.replace(/,/g, "") + data.receiveHouseNumber || "";
      // 		this.formData.Address = this.address.Address;
      // 		this.address.bool = true;
      // 		// 强制刷新
      // 		this.$forceUpdate();
      // 	}
      // });
    },
  },
};
</script>

<style lang="scss" scoped>
.root-page{
  box-sizing: border-box;
  padding: 20rpx;
  background-color: #eeeeee;
  min-height: 100vh;
  padding-bottom: 200rpx;
}
.item {
  background-color: white;
  padding: 40rpx 20rpx;
  border-radius: 10rpx;
  margin-bottom: 20rpx;

  .top {
    display: flex;
    font-weight: bold;
    font-size: 32rpx;

    .phone {
      margin-left: 60rpx;
    }

    .tag {
      display: flex;
      font-weight: normal;
      align-items: center;

      text {
        display: block;
        width: 60rpx;
        height: 34rpx;
        line-height: 34rpx;
        color: #ffffff;
        font-size: 20rpx;
        border-radius: 6rpx;
        text-align: center;
        margin-left: 30rpx;
        background-color: rgb(49, 145, 253);
      }

      .red {
        background-color: red;
      }
      .df-color {
        background-color: #00e196;
      }
    }
  }

  .bottom {
    display: flex;
    margin-top: 20rpx;
    font-size: 28rpx;
    justify-content: space-between;
    color: #999999;
  }
}

.addSite {
  display: flex;
  justify-content: space-around;
  width: 600rpx;
  line-height: 100rpx;
  position: fixed;
  bottom: 30rpx;
  left: 80rpx;
  background-color: #0175ff /* $kui-color-theme */;
  border-radius: 60rpx;
  font-size: 30rpx;

  .add {
    display: flex;
    align-items: center;
    color: #ffffff;

    .icon {
      margin-right: 10rpx;
    }
  }
}
</style>
